<template>
  <Form :model="data" :rules="rules" mode="twocolumn" ref="form">
    <FormItem label="父级编码" prop="parentSn">
      <Input type="text" v-model="data.parentSn"/>
    </FormItem>
    <FormItem label="名称" prop="name" required>
      <Input type="text" v-model="data.name"/>
    </FormItem>
    <FormItem label="自定义编码" prop="code">
      <Input type="text" v-model="data.code"/>
    </FormItem>
    <FormItem label="图标" prop="icon">
      <Input type="text" v-model="data.icon"/>
    </FormItem>
    <FormItem label="附加属性" prop="props" single>
      <div style="position: relative;height: 200px">
        <i @click="addPropItem" class="icon-plus link" style="position: absolute;right: 15px;top: 15px;z-index: 6"/>
        <Table :datas="dictProps" :height="158" style="height: 100%">
          <TableItem title="属性">
            <template #default="{data}">
              <Input v-model="data.key"/>
            </template>
          </TableItem>
          <TableItem title="值">
            <template #default="{data}">
              <Input v-model="data.value"/>
            </template>
          </TableItem>
          <TableItem title="" width="40px">
            <template #default="{data}">
              <i @click="deleteProp(data)" class="link h-icon-trash"/>
            </template>
          </TableItem>
        </Table>

      </div>
    </FormItem>
  </Form>
</template>
<script setup>
import {ajax} from 'framework'
import {ref, reactive} from 'vue'
import {message} from 'heyui'

//事件
//Props Open方法传入的参数
const {params, dialog} = defineProps({
  params: Object,
  dialog: Object
})
const dictProps = ref([])
//dialog.cancel() 方法可以直接关闭对话框
//打开Dialog时进行初始化
let isAdd = false
if (params) {
  //通知Dialog处于loading状态
  dialog.loading(true)
  ajax.get("multiDictionary/detail", params).then(r => {
    Object.assign(data, r.data)
    let props = r.data.props;
    if (props) {
      for (let s in props) {
        dictProps.value.push({key: s, value: props[s]})
      }
    }
    dialog.loading(false)
  })
} else {
  isAdd = true
}

//属性和状态
let form = ref(null)

//表单数据
const data = reactive({
  sn: null,
  parentSn: '',
  name: null,
  code: null,
  icon: null,
  props: {},
})

//验证规则
const rules = {}

/**
 * 提交数据
 */
dialog.onSubmit(() => {
  var validResult = form.value.valid();
  if (validResult.result) {
    data.props = {}
    for (let p of dictProps.value) {
      data.props[p.key] = p.value
    }

    dialog.loading(true)
    ajax.post(isAdd ? 'multiDictionary/add' : 'multiDictionary/save', data).then(r => {
      message("已保存")
      dialog.success(r.data)
    }).catch(e => {
      message.error(e.message)
    }).finally(f => dialog.loading(false))
  }
})
const addPropItem = () => {
  dictProps.value.push({key: '', value: ''})
}
const deleteProp = (item) => {
  let idx = dictProps.value.indexOf(item)
  if (idx > -1) {
    dictProps.value.splice(idx, 1)
  }
}
</script>
